<template>
  <view class="join-box">
    <view class="classification-top">
      <vanScarch class="menu-box" @on-search="onSearch" />
      <up-sticky class="filter-sticky" :offset-top="'0'" bgColor="#fff">
        <view class="filter-honour">
          <view class="filter-honour-level" @tap="handleHonourLevelFilterClick">
            <view class="text">
              荣誉等级: {{ searchParams?.grade || "不限" }}
            </view>
            <view class="icon">
              <u-icon name="arrow-down-fill" />
            </view>
          </view>
          <view class="filter-honour-year" @tap="handleHonourYearFilterClick">
            <view class="text">
              荣誉年份: {{ searchParams?.yearList?.[0] || "不限" }}
            </view>
            <view class="icon">
              <u-icon name="arrow-down-fill" />
            </view>
          </view>
          <view class="filter-honour-area" @tap="handleHonourAreaFilterClick">
            <view class="text">
              荣誉区域：{{ searchParams?.countiesList?.[0] || "不限" }}
            </view>
            <view class="icon">
              <u-icon name="arrow-down-fill" />
            </view>
          </view>
        </view>
      </up-sticky>
    </view>
    <none-data v-if="enterpriseList.length === 0" />
    <view
      v-else
      class="card-container"
      v-for="item in enterpriseList"
      :key="item.id"
    >
      <enterprise-item-card
        :card-detail="item"
        @enterprise-name-click="goEnterpriseDetail"
        @honour-total-click="handleHonourTotalClick"
        @apply-manager-click="handleApplyManagerClick"
        @join-enterprise-click="handleJoinEnterpriseClick"
      />
    </view>

    <up-popup
      :show="joinPopupData.show"
      round="33"
      @close="joinPopupClose"
      @open="open"
    >
      <view class="popup-card">
        <text class="title">
          {{ joinPopupData.title }}
        </text>
        <text class="desc">
          {{ joinPopupData.desc }}
        </text>
        <enterprise-item-card
          class="join-enterprise-popup-item-card"
          :card-detail="joinPopupData.detail"
          :show-btn-group="false"
        />
        <view class="btn" @tap="handleJoinPopupBtnClick">
          {{ joinPopupData.btnText }}
        </view>
      </view>
    </up-popup>
    <up-picker
      :show="honourLevelPickerDisabled"
      :columns="honourLevelPickerColumns"
      keyName="filedName"
      title="荣誉等级"
      :closeOnClickOverlay="true"
      :defaultIndex="honourLevelPickerDefaultIndex"
      @confirm="honourLevelPickerConfirm"
      @cancel="honourLevelPickerClosed"
      @close="honourLevelPickerClosed"
    />
    <up-picker
      :show="honourYearPickerDisabled"
      :columns="honourYearPickerColumns"
      title="荣誉年份"
      :closeOnClickOverlay="true"
      :defaultIndex="honourYearPickerDefaultIndex"
      @confirm="honourYearPickerConfirm"
      @cancel="honourYearPickerClosed"
      @close="honourYearPickerClosed"
    />
    <up-picker
      :show="honourAreaPickerDisabled"
      :columns="honourAreaPickerColumns"
      keyName="filedName"
      title="荣誉区域"
      :closeOnClickOverlay="true"
      :defaultIndex="honourAreaPickerDefaultIndex"
      @confirm="honourAreaPickerConfirm"
      @cancel="honourAreaPickerClosed"
      @close="honourAreaPickerClosed"
    />
    <u-popup
      :show="popupShowFlag"
      mode="center"
      :round="10"
      @close="popupClose"
      @open="popupOpen"
    >
      <view class="honour-total-popup">
        <view class="title">
          <h3>{{ honourTotal }}</h3>
          <h5>项荣誉</h5>
        </view>
        <view class="honour-list">
          <view
            class="honour-item"
            v-for="(item, index) in honourTotalDataList"
            :key="index"
          >
            <view class="label">
              {{ item.label }}
            </view>
            <view class="value">
              <h4>
                {{ item.value }}
              </h4>
              <h5>项</h5>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
    <uni-popup
      ref="goRealNameAuthenticationPopupRef"
      type="center"
      round
      popupStyles="z-index: 99999;"
      background-color="#fff"
      @mask-click="handleCloseGoRealNamePopup"
    >
      <view class="go-real-name-authentication-popup">
        <view class="go-real-name-authentication-popup-text">
          您还未实名认证
        </view>
        <view
          class="go-real-name-authentication-popup-btn"
          @click="goRealNamePage"
        >
          去实名认证
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, watch, inject } from "vue";
import { joinEnterpriseApi } from "@/api/user/index.js";
import { getUserInfoApi } from "@/api/user";
import vanScarch from "./componments/van-scarch.vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import {
  getAppEnterpriseListApi,
  getConfigEnterpriseFieldsApi,
  getEnterpriseHonorCountDetailsApi,
  getHonourYearsListApi,
} from "@/api/honour/search";
import EnterpriseItemCard from "@/package_user/pages/user/components/enterprise-item-card.vue";
import { getEnterpriseHonorCountSortMapApi } from "@/api/honour/enterprise-list";
import { customNav } from "@/utils/customNav";

const packageHonourPath = inject("packageHonourPath");
const goRealNameAuthenticationPopupRef = ref();
const enterpriseId = ref("");
const honorList = ref([]);
const imageUrl = ref();
const isLoading = ref(false);
const userInfo = ref({});
// 记录公司总条数
const total = ref(0);

const joinPopupData = reactive({
  show: false,
  title: "",
  desc: "",
  detail: {},
  btnText: "",
});
const joinPopupClose = () => {
  joinPopupData.show = false;
};

/**
 * 申请管理员按钮点击事件监听
 * @param item 当前企业项
 * @returns {Promise<void>}
 */
const handleApplyManagerClick = async (item) => {
  const params = {
    enterpriseName: item.enterpriseName,
    page: 1,
    size: 10,
  };
  const res = await getAppEnterpriseListApi(params);
  const { code, data } = res;
  if (code === 200) {
    const { records } = data;
    const curEnterprise = records[0];
    enterpriseId.value = curEnterprise.id;
    joinPopupData.show = true;
    joinPopupData.title = "申请管理员";
    joinPopupData.desc =
      "当前企业尚无管理员，暂无法加入，现在就申请成为企业管理员？";
    joinPopupData.btnText = "立即申请";
    joinPopupData.detail = { ...curEnterprise };
  }
};

/**
 * 申请加入按钮点击事件监听
 * @param item 当前企业项
 * @returns {Promise<void>}
 */
const handleJoinEnterpriseClick = async (item) => {
  const params = {
    enterpriseName: item.enterpriseName,
    page: 1,
    size: 10,
  };
  const res = await getAppEnterpriseListApi(params);
  const { code, data } = res;
  if (code === 200) {
    const { records } = data;
    const curEnterprise = records[0];
    enterpriseId.value = curEnterprise.id;
    imageUrl.value = curEnterprise.avatar;
    curEnterprise.enterpriseHonorInfoList?.map((o) => {
      honorList.value.push(o.enterpriseHonor);
    });
    joinPopupData.show = true;
    joinPopupData.title = "申请加入";
    joinPopupData.desc =
      "你确定要加入以下企业吗？请确保你是该企业的员工，以免审核无法通过";
    joinPopupData.btnText = "申请加入";
    joinPopupData.detail = { ...curEnterprise };
  }
};

/**
 * 弹窗申请加入、申请管理员按钮监听
 */
const handleJoinPopupBtnClick = () => {
  const { title } = joinPopupData;
  if (userInfo.value.hasIdCard) {
    switch (title) {
      case "申请加入":
        joinEnterprise();
        break;
      case "申请管理员":
        customNav(
          `/package_user/pages/user/administratorApply?enterpriseName=${joinPopupData.detail.enterpriseName}&id=${enterpriseId.value}`
        );
        break;
    }
  } else {
    goRealNameAuthenticationPopupRef.value.open();
  }
};

/**
 * 获取用户信息
 * @returns {Promise<void>}
 */
const getUserInfo = async () => {
  const res = await getUserInfoApi();
  const { code, data } = res;
  if (code === 200) {
    userInfo.value = data;
    if (userInfo.value.hasIdCard) {
      goRealNameAuthenticationPopupRef.value.close();
    }
    // console.log("userInfo.value",userInfo.value);
  }
};
/**
 * 加入企业接口
 * @returns {Promise<void>}
 */
const joinEnterprise = async () => {
  const res = await joinEnterpriseApi(enterpriseId.value);
  const { code, msg } = res;
  if (code === 200) {
    await uni.showToast({
      title: "加入成功",
      duration: 2000,
    });
    joinPopupData.show = false;
  } else if (code === 400) {
    await uni.showToast({
      title: msg,
      icon: "error",
      duration: 2000,
    });
  }
};
/**
 * 跳转到实名认证页面
 */
const goRealNamePage = () => {
  customNav("/package_user/pages/user/name-authentication");
};
function onSearch(data) {
  enterpriseList.value = [];
  searchParams.value.enterpriseName = data;
  resetSearchParamsPageAndSize();
  getEnterpriseList();
}

/**
 * 跳转企业详情页面
 * @param enterprise 当前点击企业
 */
const goEnterpriseDetail = (enterprise) => {
  customNav(
    `${packageHonourPath}/enterprise-honor-detail?name=${enterprise.enterpriseName}&&typeName=企业&&id=${enterprise.id}`
  );
};

/* 列表筛选部分start */
let searchParams = ref({
  enterpriseName: "",
  grade: "",
  yearList: [],
  countiesList: [],
  page: 1,
  size: 10,
});
const curSearchName = ref("");
const enterpriseList = ref([]);
const curPage = ref(1);
const curPageSize = ref(10);
const totalPages = ref(0);
/**
 * 重置搜索数据的page和pageSize
 */
const resetSearchParamsPageAndSize = () => {
  curPage.value = 1;
  curPageSize.value = 10;
};
/* 荣耀等级筛选部分start */
const honourLevelPickerDisabled = ref(false);
const honourLevelPickerColumns = reactive([]);
let honourLevelPickerDefaultIndex = reactive([0]);

/**
 * 荣耀等级筛选点击事件
 */
const handleHonourLevelFilterClick = () => {
  const curHonourLevel = searchParams.value.grade || "不限";
  const selectEdIndex = honourLevelPickerColumns[0].findIndex(
    (item) => item.filedName === curHonourLevel
  );
  if (selectEdIndex !== -1) {
    honourLevelPickerDefaultIndex = [selectEdIndex];
  }
  honourLevelPickerDisabled.value = true;
};
/**
 * 确定按钮点击事件监听
 */
const honourLevelPickerConfirm = (e) => {
  enterpriseList.value = [];
  const selectedVal = e.value[0].filedName;
  const findSelected = honourLevelPickerColumns[0].find(
    (item) => item.filedName === selectedVal
  );
  searchParams.value.grade =
    selectedVal === "不限" ? "" : findSelected.filedName;
  honourLevelPickerClosed();
};

/**
 * 取消按钮点击事件和mask层点击事件监听
 */
const honourLevelPickerClosed = () => {
  honourLevelPickerDisabled.value = false;
};
watch(
  () => searchParams.value.grade,
  (newVal, oldVal) => {
    let hasChange;
    const isFirstIn = oldVal === undefined;
    if (newVal?.length === 0 && oldVal?.length === 0) {
      hasChange = false;
    } else {
      hasChange = newVal !== oldVal;
    }
    !isFirstIn && hasChange && resetSearchParamsPageAndSize();
    !isFirstIn && hasChange && getEnterpriseList();
  },
  { deep: true, immediate: false }
);

/* 荣耀等级筛选部分end */

/* 荣耀年份筛选部分 start */
const honourYearPickerDisabled = ref(false);
const honourYearPickerColumns = reactive([]);
let honourYearPickerDefaultIndex = reactive([0]);
/**
 * 荣耀年份筛选点击事件
 */
const handleHonourYearFilterClick = () => {
  const curHonourYear = searchParams.value.yearList?.[0] || "不限";
  const selectEdIndex = honourYearPickerColumns[0].findIndex(
    (item) => item === curHonourYear
  );
  if (selectEdIndex !== -1) {
    honourYearPickerDefaultIndex = [selectEdIndex];
  }
  honourYearPickerDisabled.value = true;
};
/**
 * 取消按钮点击事件和mask层点击事件监听
 */
const honourYearPickerClosed = () => {
  honourYearPickerDisabled.value = false;
};

/**
 * 确定按钮点击事件监听
 */
const honourYearPickerConfirm = (e) => {
  console.log(e);
  enterpriseList.value = [];
  const selectedVal = e.value[0];
  const findSelected = honourYearPickerColumns[0].find(
    (item) => item === selectedVal
  );

  searchParams.value.yearList = findSelected === "不限" ? [] : [findSelected];
  honourYearPickerClosed();
};

/**
 * 获取荣耀年份数据列表
 * @returns {Promise<void>}
 */
const getHonourYearsDataList = async () => {
  const res = await getConfigEnterpriseFieldsApi({
    type: "企业荣誉年份",
  });
  const { code, data } = res;
  if (code === 200) {
    const yearList = data[0].children.map((o) => {
      return o.filedName;
    });
    honourYearPickerColumns[0] = yearList;
    honourYearPickerColumns[0].push("不限");
  }
};
watch(
  () => searchParams.value.yearList,
  (newVal, oldVal) => {
    let hasChange;
    const isFirstIn = !oldVal;
    if (newVal?.length === 0 && oldVal?.length === 0) {
      hasChange = false;
    } else {
      hasChange = newVal !== oldVal;
    }
    !isFirstIn && hasChange && resetSearchParamsPageAndSize();
    !isFirstIn && hasChange && getEnterpriseList();
  },
  { deep: true }
);
/* 荣耀年份筛选部分end */

/* 荣耀地区筛选部分start */
const honourAreaPickerDisabled = ref(false);
const honourAreaPickerColumns = reactive([]);
let honourAreaPickerDefaultIndex = reactive([0]);

/**
 * 荣耀地区筛选点击事件
 */
const handleHonourAreaFilterClick = () => {
  const curHonourArea = searchParams.value.countiesList || "不限";
  const selectEdIndex = honourAreaPickerColumns[0].findIndex(
    (item) => item.filedName === curHonourArea
  );
  if (selectEdIndex !== -1) {
    honourAreaPickerDefaultIndex = [selectEdIndex];
  }
  honourAreaPickerDisabled.value = true;
};
/**
 * 确定按钮点击事件监听
 */
const honourAreaPickerConfirm = (e) => {
  enterpriseList.value = [];
  const selectedVal = e.value[0].filedName;
  const findSelected = honourAreaPickerColumns[0].find(
    (item) => item.filedName === selectedVal
  );
  searchParams.value.countiesList =
    findSelected.filedName === "不限" ? [] : [findSelected.filedName];
  honourAreaPickerClosed();
};

/**
 * 取消按钮点击事件和mask层点击事件监听
 */
const honourAreaPickerClosed = () => {
  honourAreaPickerDisabled.value = false;
};
watch(
  () => searchParams.value.countiesList,
  (newVal, oldVal) => {
    // console.log('新数据',newVal)
    // console.log('老数据', oldVal)
    let hasChange;
    const isFirstIn = !oldVal;
    if (newVal?.length === 0 && oldVal?.length === 0) {
      hasChange = false;
    } else {
      hasChange = newVal !== oldVal;
    }
    !isFirstIn && hasChange && resetSearchParamsPageAndSize();
    !isFirstIn && hasChange && getEnterpriseList();
  },
  { deep: true, immediate: false }
);
/* 荣耀地区筛选部分end */

/**
 * 获取荣耀等级和荣耀区域总数据
 * @returns {Promise<void>}
 */
const getFilterDataList = async () => {
  const res = await getConfigEnterpriseFieldsApi({ type: 0 });
  const { code, data } = res;
  if (code === 200) {
    honourLevelPickerColumns[0] = data.find(
      (item) => item.filedName === "荣誉等级"
    )?.children;
    honourLevelPickerColumns[0].push({
      filedName: "不限",
    });
    honourAreaPickerColumns[0] = data.find(
      (item) => item.filedName === "荣誉区域"
    )?.children;
    honourAreaPickerColumns[0].push({
      filedName: "不限",
    });
  }
};
/* 列表筛选部分end */

/* 弹出层部分start*/
const popupShowFlag = ref(false);
const popupOpen = () => {};
const popupClose = () => {
  popupShowFlag.value = false;
};
const honourTotalDataList = ref([]);
const honourTotal = ref(0);
const honorMap = ref({});
/**
 * 企业卡片荣誉总数按钮监听
 * @param enterpriseName 企业名称
 */
const handleHonourTotalClick = (enterpriseName) => {
  getHonorTotalSortKey(enterpriseName);
};

/**
 * 获取企业荣誉排序map
 * @param enterpriseName
 * @returns {Promise<void>}
 */
const getHonorTotalSortKey = async (enterpriseName) => {
  const res = await getEnterpriseHonorCountSortMapApi();
  const { code, data } = res;
  if (code === 200) {
    const validKeys = data;
    honorMap.value = data
      .filter((key) => validKeys.includes(key))
      .reduce((acc, key) => {
        acc[key] = "";
        return acc;
      }, {});
    await getHonorTotalData(enterpriseName);
  }
};

/**
 * 获取企业荣誉详情
 * @param enterpriseName 企业名称
 * @returns {Promise<void>}
 */
const getHonorTotalData = async (enterpriseName) => {
  const res = await getEnterpriseHonorCountDetailsApi({ enterpriseName });
  const { code, data } = res;
  if (code === 200) {
    honourTotal.value = data["总数"];
    const orderKeys = Object.keys(honorMap.value);
    const orderData = orderKeys.reduce((acc, key) => {
      acc[key] = data[key] || "0";
      return acc;
    }, {});
    honourTotalDataList.value = Object.keys(orderData)
      .map((key) => {
        if (key !== "总数") {
          return { label: key, value: data[key] };
        }
        return null;
      })
      .filter((item) => item !== null);
    popupShowFlag.value = true;
  }
};
/* 弹出层部分end */

onLoad(() => {
  getEnterpriseList();
  getFilterDataList();
  getHonourYearsDataList();
});
onShow(() => {
  getUserInfo();
});
/**
 * 获取企业列表
 * @returns {Promise<void>}
 */
const getEnterpriseList = async () => {
  const params = Object.assign(searchParams.value, {
    page: curPage.value,
    size: curPageSize.value,
  });
  const res = await getAppEnterpriseListApi(params);
  const { code, data } = res;
  if (code === 200) {
    const { pages, records } = data || {};
    totalPages.value = pages;
    if (enterpriseList.value.length === 0) {
      enterpriseList.value = records;
    } else {
      enterpriseList.value = enterpriseList.value.concat(records);
    }
  }
};
onReachBottom(async () => {
  if (curPage.value <= totalPages.value) {
    curPage.value++;
    await getEnterpriseList();
  }
});
</script>

<style scoped lang="less">
.join-box {
  .classification-top {
    margin-top: 20rpx;

    :deep(.u-sticky) {
      top: 0 !important;
      padding: 0 36rpx !important;
      z-index: 9 !important;
      margin-top: 30rpx;
    }

    .filter-honour {
      display: flex;

      &-level,
      &-year,
      &-area {
        display: flex;
        margin: 30rpx 0 60rpx 0;
        font-family: "ali-m";
        font-weight: 500;
        color: #272636;
        font-size: 24rpx;

        .text {
          flex: 1;
        }

        .icon {
          margin-left: 10rpx;

          .u-icon {
            :deep(.u-icon__icon) {
              font-size: 24rpx !important;
              font-weight: 700;
              color: #272636 !important;
            }
          }
        }
      }

      &-year {
        margin-left: 25rpx;
        margin-right: 25rpx;
      }

      &-area {
        flex: 1;

        .text {
          text-align: end;
        }
      }
    }
  }

  .card-container {
    padding: 0 30rpx;
    background-color: #fff;
  }

  .honour-total-popup {
    width: 260rpx;
    padding: 19rpx 24rpx 35rpx 21rpx;
    box-shadow: 0 2rpx 13rpx 0 rgba(85, 144, 246, 0.5);
    border: 1px solid #5590f6;
    border-right: 7rpx;

    .title {
      display: flex;
      align-items: center;
      height: 30rpx;

      h3 {
        font-family: "DIN";
        font-weight: bold;
        font-size: 31rpx;
        color: #ff9c00;
      }

      h5 {
        font-family: "ali-m";
        font-weight: 400;
        font-size: 23rpx;
        color: #272636;
        margin-left: 8rpx;
      }
    }

    .honour-list {
      margin-top: 38rpx;

      .honour-item {
        display: flex;

        .label {
          flex: 1;
          font-family: "ali-m";
          font-weight: 400;
          font-size: 23rpx;
          color: #272636;
        }

        .value {
          display: flex;
          flex: 1;

          h4 {
            flex: 1;
            text-align: end;
            font-family: "DIN";
            font-weight: bold;
            font-size: 23rpx;
            color: #ff9c00;
          }

          h5 {
            flex: 1;
            text-align: start;
            font-family: "ali-m";
            font-weight: 400;
            font-size: 23rpx;
            color: #272636;
            margin-left: 12rpx;
          }
        }
      }
    }
  }
  :deep(.u-picker) {
    height: 400rpx;
  }
  .popup-card {
    width: 100vw;
    height: 720rpx;
    display: flex;
    flex-direction: column;
    padding: 32rpx;
    box-sizing: border-box;
    font-family: "ali-p";

    .title {
      font-size: 31rpx;
      font-weight: 400;
      color: @color-black-text;
      text-align: center;
    }

    .desc {
      font-size: 31rpx;
      font-weight: 400;
      color: @color-light-grey-text;
      line-height: 47rpx;
      margin-top: 67rpx;
      padding-bottom: 37rpx;
      border-bottom: 2px solid @color-light-grey-border;
    }

    :deep(.join-enterprise-popup-item-card) {
      margin-top: 22rpx;
      padding-bottom: 50rpx;
      .enterprise-item-card {
        border-bottom: none;
      }
    }

    .btn {
      position: absolute;
      bottom: 35rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 697rpx;
      height: 80rpx;
      background: linear-gradient(90deg, #ff934c 0%, #fc686f 100%);
      border-radius: 16rpx;
      font-family: "ali-p";
      font-weight: 500;
      font-size: 31rpx;
      color: @color-origin-white;
      line-height: 80rpx;
      text-align: center;
    }
  }
}
.go-real-name-authentication-popup {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  width: 40vw;
  height: 300rpx;
  border-radius: 40rpx;
  padding: 20rpx 40rpx;
  font-family: "ali";

  &-text {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
    font-weight: 600;
  }

  &-btn {
    width: 100%;
    height: 60rpx;
    line-height: 60rpx;
    color: #fff;
    font-weight: 700;
    text-align: center;
    background-color: #00a4ff;
    border-radius: 40rpx;
  }
}
</style>
